<template>
  <div>
    购物车
    <van-checkbox-group v-model="result" ref="checkboxGroup" @change="checkBoxChange">
      <div v-for="item in cart_list" :key="item.id">
        <van-checkbox :name="item.id"></van-checkbox>
        {{item.title}} {{item.price}} 元
        <span v-show="item.cartnum>=1">
          <button @click="removeCart(item)">-</button>
          {{item.cartnum}}
        </span>
        <button @click="ADD_CART(item)">+</button>
        小计： {{item.price*item.cartnum}}
        <van-divider />
      </div>
    </van-checkbox-group>

    购物车总计：{{totalPrice}} 元
    选中总计:{{total}} 元
    <van-button type="primary" @click="checkAll">全选</van-button>
    <van-button type="info" @click="toggleAll">反选</van-button>
  </div>
</template>
<script>
import { mapGetters, mapMutations, mapState } from "vuex";
export default {
  data() {
    return {
      result: []
    };
  },
  computed: {
    ...mapState(["cart_list"]),
    ...mapGetters(["totalPrice"]),
     total() {
       console.log('total...result',this.result);

      let money = 0;
      this.result.forEach((checkedId) => {
         
       
            let index=this.cart_list.findIndex((item)=>item.id+''===checkedId+'');
            console.log('index',index);
          
          money += this.cart_list[index].price * this.cart_list[index].cartnum;
          
        });

        return money;
    },
  },
  methods: {
    ...mapMutations(["ADD_CART", "REMOVE_CART"]),
    checkBoxChange(){
        console.log('result',this.result);
    },
    removeCart(item){
      // 将checkbox-group中选中的值this.result绑定到item对象中 一起传给vuex mutations方法 RMOVE_CART
      item.result=this.result;
      this.REMOVE_CART(item)
     
     
    },
    checkAll() {
     
      this.$refs.checkboxGroup.toggleAll(true);
    
    },
    toggleAll() {
   
       this.$refs.checkboxGroup.toggleAll();
    
    },

   

   
  },
};
</script>